class Sum {
    private static int even_sum = 0;
    private static int odd_sum = 0;
    private Object locker = new Object();
    public void even_add(int n) {
        synchronized (locker) {
            even_sum += n;
        }
    }
    public void odd_add(int n) {
        synchronized (locker) {
            odd_sum += n;
        }
    }
    public int get_even_sum() {
        return even_sum;
    }
    public int get_odd_sum() {
        return odd_sum;
    }
}
public class ThreadDemo2 {
    public static void main(String[] args) throws InterruptedException {
        long stime = System.currentTimeMillis();
        int[] array = new int[1000_0000];
        for (int i = 0; i < 1000_0000; i++) {
            array[i] = (int)( 1 + Math.random() * 100);
        }
        Sum sum = new Sum();
        Thread t1 = new Thread( () -> {
            for (int i = 0; i < 1000_0000; i++) {
                if(i % 2 == 0) {
                    sum.even_add(array[i]);
                }
            }
        });
        Thread t2 = new Thread( ()-> {
            for (int i = 0; i < 1000_0000; i++) {
                if(i % 2 == 1) {
                    sum.odd_add(array[i]);
                }
            }
        });


        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println(sum.get_even_sum()+sum.get_odd_sum());
        long etime = System.currentTimeMillis();
        System.out.println("执行时长："+(etime - stime)+" 毫秒");
    }
}
